using System;
using System.ComponentModel;
using System.Data;
using System.Reflection;

namespace Wantn.Share
{
	public class EnumOpt
	{
		public static DataTable Enum2Datatable(Type enumType)
		{
			if (!enumType.IsEnum)
			{
				throw new Exception("enumType参数必须为枚举类型");
			}
			DataTable dataTable = new DataTable();
			dataTable.Columns.AddRange(new DataColumn[3]
			{
				new DataColumn("Id", typeof(int)),
				new DataColumn("Name", typeof(string)),
				new DataColumn("Desc", typeof(string))
			});
			dataTable.Columns["Id"].Unique = true;
			FieldInfo[] fields = enumType.GetFields();
			FieldInfo[] array = fields;
			foreach (FieldInfo fieldInfo in array)
			{
				if (!fieldInfo.FieldType.IsEnum)
				{
					continue;
				}
				int num = Convert.ToInt32(fieldInfo.GetRawConstantValue());
				string name = fieldInfo.Name;
				string text = name;
				object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), inherit: false);
				if (customAttributes != null && customAttributes.Length > 0)
				{
					DescriptionAttribute descriptionAttribute = customAttributes[0] as DescriptionAttribute;
					if (descriptionAttribute != null)
					{
						text = descriptionAttribute.Description;
					}
				}
				dataTable.Rows.Add(num, name, text);
			}
			return dataTable;
		}

		public static string GetEnumDesc(object enumValue)
		{
			if (enumValue == null)
			{
				throw new Exception("enumValue参数不能为空");
			}
			string text = enumValue.ToString();
			FieldInfo field = enumValue.GetType().GetField(text);
			if (field != null && field.FieldType.IsEnum)
			{
				object[] customAttributes = field.GetCustomAttributes(typeof(DescriptionAttribute), inherit: false);
				if (customAttributes != null && customAttributes.Length > 0)
				{
					DescriptionAttribute descriptionAttribute = customAttributes[0] as DescriptionAttribute;
					if (descriptionAttribute != null)
					{
						text = descriptionAttribute.Description;
					}
				}
				return text;
			}
			throw new Exception("enumValue参数不能为非枚举类型");
		}

	}
}
